import axios from 'axios'
import { Message } from 'element-ui'
import Vue from 'vue'

Vue.prototype.$axios = axios

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 15000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 发送请求之前做的事
    if (config.method === 'post') {
      config.headers['Content-Type'] = 'application/json; charset=utf-8';
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.headers['content-type'] === 'application/octet-stream; charset=utf-8' ||
        response.headers['content-type'] === 'application/octet-stream') {
      return response;
    }
    const res = response.data;
    let status = res.statuscode || response.status;
    if (status !== 200 && status !== 204) {
      let showText = '';
      if(typeof(res.errors)==='string') {
        showText = res.errors;
      } else if(typeof(res.errors)==='object') {
        for(let key in res.errors) {
          if(typeof(res.errors[key])==='string') {
            showText = res.errors[key];
          } else {
            showText = res.errors[key][0];
          }
          break;
        }
      }
      Message({
        message: showText || 'Error',
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
)

export const request = (url, method = 'POST', data = {}, responseType = 'json', timeout = 15000) => {
  // timeout为接口等待时间
  service.defaults.timeout = timeout;
  const reConfig = url !== '/api/codegenerator/testconnection' ? {
    url,
    method,
    params: data,
    responseType
  } : {
    url,
    method,
    data
  }
  return service(reConfig)
}

export default request
